﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Steve
{
    public enum CacheType
    {
        Other = 0,
        Url,
        ContentDirectory,
        ContentType,
        Category,
        SearchIndex
    };

    public interface ICacheService
    {
        T GetValue<T>(CacheType cacheType, string cacheKey) where T : class;
        void PutValue(CacheType cacheType, string cacheKey, object value, TimeSpan? ttl);
        void Invalidate(CacheType cacheType, string cacheKey);
        void Invalidate(CacheType cacheType);
        IEnumerable<string> GetKeys(CacheType cacheType);
    }

    public static class CacheServiceExtensions
    {
        //TODO: thread safety? maybe not an issue...
        /// <remarks>Attempts Get and if not present, performs load and then saves via Put</remarks>
        public static T GetValue<T>(this ICacheService cache, CacheType cacheType, string cacheKey, TimeSpan? ttl, Func<T> load) where T : class
        {
            if (cache == null) throw new ArgumentNullException("cache");
            if (load == null) throw new ArgumentNullException("load");

            var obj = cache.GetValue<T>(cacheType, cacheKey);

            if (obj == null)
            {
                obj = load();
                cache.PutValue(cacheType, cacheKey, obj, ttl);
            }

            return obj;
        }
    }
}
